<?php
/**
 * Created by PhpStorm.
 * User: xpz
 * Date: 2025/3/12
 * Time: 10:11
 */

namespace app\admin\controller;
use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\Cache;
class Article extends Backend
{
    protected $model = null;
    protected $categoryModel = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('app\admin\model\Article');
        $this->categoryModel = model('app\common\model\Category');
        list($where, $sort, $order, $offset, $limit) = $this->buildparams('name');
        $tree = Tree::instance();
        $tree->init(collection($this->categoryModel->order('weigh desc,id desc')->where($where)->select())->toArray(), 'pid');
        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $categorydata = [0 => ['type' => 'all', 'name' => __('None')]];
        foreach ($this->categorylist as $k => $v) {
            $categorydata[$v['id']] = $v;
        }
        $this->view->assign("parentList", $categorydata);
    }
    public function index() {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
//        print_r($this->request);exit;
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('title');
//            print_r($order);
//            print_r($sort);
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
//        return $this->view->fetch('', ['url' => Tool::get_url(), 'group_id' => 1]);
    }


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                //获取分类父ID
                list($params['category_pid'],$params['category_name']) = $this->_getCategoryPid($params['category_id']);
                //处理简介
                $params['summary'] = $this->_summary($params['summary'],$params['content']);
                //url路径处理
                $params['url_path'] = $this->_urlPath($params['url_path'],$params['title']);
                //添加作者
                $params['author'] = getAuthor();
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    $aid = $this->model->getLastInsID();
                    $this->_insertContent($aid,$params['content']);
                    Db::commit();

                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->_mvImage($aid);
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                //获取分类父ID
                list($params['category_pid'],$params['category_name']) = $this->_getCategoryPid($params['category_id']);
                //处理简介
                $params['summary'] = $this->_summary($params['summary'],$params['content']);
                //url路径处理
                $params['url_path'] = $this->_urlPath($params['url_path'],$params['title'],$ids);
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    $this->_insertContent($row['id'],$params['content']);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->_mvImage($row['id']);
                    Cache::rm('article_details_cache_'.$params['url_path']);
                    Cache::rm('article_details_content_cache_'.$row['id']);
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        $this->view->assign('content',$this->_getContent($ids));
        return $this->view->fetch();
    }


    private function _getContent($id){
        $contentModel = model('app\common\model\ArticleContent');
        $data = $contentModel->where(['aid'=>$id])->find();
        if(!empty($data) && !empty($data['content'])){
            return $data['content'];
        }
        return "";
    }

    private function _getCategoryPid($categoryId){
        $data = $this->categoryModel->where(['id'=>$categoryId])->find();


        if(!empty($data)){
            return [$data['pid'],$data['name']];
        } else {
            return [0,''];
        }
    }

    private function _insertContent($aid,$content){
        $content = filterContent($content);
        $contentModel = model('app\common\model\ArticleContent');
        $data = $contentModel->where(['aid'=>$aid])->find();
        if(!empty($data)){
            $contentModel->where(['id'=>$data['id']])->update(['content'=>$content]);
        } else {
            $contentModel->aid = $aid;
            $contentModel->content = $content;
            $contentModel->save();
        }

    }

    private function _summary($summary,$content){
        if(!empty($summary)){
            return $summary;
        } else {
            return str_cut($content);
        }
    }

    private function _urlPath($urlPath,$title,$isAdd=0){
        if(!empty($urlPath)){
            $return = $urlPath;
        } else {
            $return = $title;
        }
        $return = filterSpecialChars($return);
        $return = str_replace(' ','-',$return);
        $where = ['url_path'=>$return];
        $data = $this->model->where($where)->find();
        if($isAdd == 0){
            if(!empty($data)){
                $this->error('urlPath路径已存在，请修改！');
            }
        } else {
            if(!empty($data) && $data['id'] != $isAdd){
                $this->error('urlPath路径已存在，请修改！');
            }
        }

        return $return;
    }



    private function _mvImage($aid){
        $mvmodel = model('app\common\model\Mvimage');
        $articleData = $this->model->where(['id'=>$aid])->find();
//        var_dump($articleData['image']);exit;
        if(!empty($articleData['image'])){
            // 获取文件名（带扩展名）
            $filename = basename($articleData['image']);
            // 分离文件名和扩展名
            $hash = pathinfo($filename, PATHINFO_FILENAME);
//            echo $hash;exit;
            if (strpos($hash, '-') !== false) {

//                echo "字符串包含减号";
            } else {
                $mvmodel->save(['aid'=>$aid]);
//                echo "字符串不包含减号";
            }

//            if (ctype_digit($hash)) {
////                echo "字符串全是数字";
//                $mvmodel->save(['aid'=>$aid]);
//            } else {
////                echo "包含非数字字符";
//            }
        }
    }
}